package com.kx.project.exam.service.impl;

import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;

import com.kx.platform.caffeine.CaffeineCacheServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kx.common.constant.Constants;
import com.kx.common.constant.UserConstants;
import com.kx.common.core.text.Convert;
import com.kx.common.exception.CustomException;
import com.kx.common.utils.StringUtils;
import com.kx.project.exam.domain.Question;
import com.kx.project.exam.mapper.QuestionMapper;
import com.kx.project.exam.service.QuestionService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 题目 服务层实现
 * 
 * @author kx  
 */
@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    /**
     * 启动时，初始化到缓存
     */
    @PostConstruct
    public void init() { }

    /**
     * 查询题目列表
     * 
     * @param question 题目信息
     * @return 题目集合
     */
    @Override
    public List<Question> listByPage(Question question)
    {
        return questionMapper.listByPage(question);
    }

    /**
     * 查询题目信息
     *
     * @param id 题目ID
     * @return 题目信息
     */
    @Override
    public Question getById(Long id)
    {
        Question question = new Question();
        question.setId(id);
        return questionMapper.getById(question);
    }

    /**
     * 新增题目
     * 
     * @param question 题目信息
     * @return 结果
     */
    @Override
    public int insert(Question question) {
        question.setCreateTime(new Date());
        question.setUpdateTime(new Date());

        int row = questionMapper.insert(question);
        return row;
    }

    /**
     * 修改题目
     * 
     * @param question 题目信息
     * @return 结果
     */
    @Override
    public int update(Question question) {
        question.setUpdateTime(new Date());
        int row = questionMapper.update(question);
        return row;
    }

    /**
     * 批量删除
     *
     * @param ids 需要删除的IDS
     * @return 结果
     */
    @Override
    public int removeByIds(Long[] ids) {
        if(ids != null && ids.length > 0){
            for (Long id : ids){
                questionMapper.removeById(id);
            }
        }
        return 1;
    }

    /**
     * 校验是否唯一
     * 
     * @param question 题目信息
     * @return 结果
     */
    @Override
    public String checkUnique(Question question)
    {
        Long id = StringUtils.isNull(question.getId()) ? -1L : question.getId();

        Question info = questionMapper.checkUnique(question.getQuestionName());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
